package com.imooc.course;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

@EnableDiscoveryClient
@SpringBootApplication
//@EnableEurekaClient
public class GatewayApplication {


    private static final Logger log = LoggerFactory.getLogger(GatewayApplication.class);

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(GatewayApplication.class);
        Environment env = app.run(args).getEnvironment();
        log.info("启动成功！");
        log.info("gateway地址：\thttp://127.0.0.1:{}",env.getProperty("server.port"));
    }

    /**
     * 由gateway网关统一解决跨域
     * @return CorsWebFilter
     */
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();

        config.setAllowCredentials(Boolean.TRUE);//允许携带cookie跨域
        config.addAllowedMethod("*");//允许哪种方式（get/post）跨域
        config.addAllowedOrigin("*");//允许哪些请求来源跨域
        config.addAllowedHeader("*");//允许哪些请求头跨域
        config.setMaxAge(3600L);//预检请求的缓存时间（秒），即在这个时间段里，对于相同的跨域请求不会再预检了

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        //允许哪些路径应用以上的跨域配置。
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}
